package com.intelligentmeterreadingsys.report.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.httpserver.UploadHttpClient;
import com.intelligentmeterreadingsys.povo.EngineeringOrderPoVo;
import com.intelligentmeterreadingsys.povo.TypePoVo;
import com.intelligentmeterreadingsys.povo.UserWaterVO;
import com.intelligentmeterreadingsys.report.db.ReportDao;
import com.intelligentmeterreadingsys.util.FileNameUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;

import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;

/**
 * 读卡异常报案
 * 
 * @author king
 * 
 */
public class ReportNoRFIDActivity extends Activity implements OnClickListener,
		OnTouchListener, OnGestureListener {
	private static final int REQUEST_CODE_TAKE_VIDEO = 2;
	private static final int REQUEST_CODE_TAKE_IMAGE = 1;
	private static final int REQUEST_CODE_TAKE_SOUND = 3;
	private final static int DIALOG = 1;
	public static final int ITEM0 = Menu.FIRST;// 系统值

	public Button button3;// 保存
	public Button button4;// 修改
	public Button button5;// 上传
	public Button button6;// 查询
	public Double latitude = 0.0;// 维度
	public Double longitude = 0.0;// 径度
	public EditText edit2;// 工程单名称
	public EditText edit3;// 工程单描述
	public Spinner spinner;// 工程单类型
	public TextView textview1;// 水表编号
	public TextView textview2;// 水表地址
	public String videopath = "";
	public GestureDetector mGestureDetector;
	// 手势移动量
	private int verticalMinDistance = 30;
	private int minVelocity = 0;

	public List<String> imgpath;
	public String soundpath = "";

	public String type;

	public int OrderID = 0;

	public ProgressDialog pd;

	public List<UserWaterVO> list = null;
	public int i = 0;
	public boolean isupload = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_norfid);
		init();
	}

	/**
	 * 初始化控件
	 */
	public void init() {
		String waterid = getIntent().getStringExtra("waterid");

		button3 = (Button) findViewById(R.id.order_norfid_save);
		button4 = (Button) findViewById(R.id.order_norfid_modify);
		button5 = (Button) findViewById(R.id.order_norfid_upload);

		button3.setOnClickListener(this);
		button4.setOnClickListener(this);
		button5.setOnClickListener(this);

		textview2 = (TextView) findViewById(R.id.order_norfid_textview_wateradds);
		textview1 = (TextView) findViewById(R.id.order_norfid_textView_waternumber);
		textview1.setText("");
		textview2.setText("");

		edit2 = (EditText) findViewById(R.id.order_norfid_ordername);
		edit3 = (EditText) findViewById(R.id.order_norfid_desc);
		spinner = (Spinner) findViewById(R.id.order_norfid_ordertype);

		// 选择工程类型监听器
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				type = arg0.getItemAtPosition(arg2).toString();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				type = "无";

			}
		});

		ReportDao dao = new ReportDao(this);

		List<TypePoVo> list = dao.queryOrderType();
		String date[] = null;
		if (list != null && list.size() > 0) {
			date = new String[list.size() + 1];
			date[0] = "请选择";
			for (int i = 0; i < list.size(); i++) {
				date[i + 1] = list.get(i).getName();
			}
		} else {
			date = new String[] { "请选择" };
		}

		dao.close();

		// 初始化下拉框数据
		ArrayAdapter<String> ada = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, date);// 放数据
		ada.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(ada);
		// 添加手势
		mGestureDetector = new GestureDetector((OnGestureListener) this);
		RelativeLayout layout = (RelativeLayout) findViewById(R.id.order_norfid_relativelayout);
		layout.setOnTouchListener(this);
		layout.setLongClickable(true);
		System.out.println("waterid" + waterid);
		if (!TextUtils.isEmpty(waterid)) {

			ReportDao waterdao = new ReportDao(ReportNoRFIDActivity.this);
			this.list = waterdao.queryUserWaterInfo(null, waterid);

			waterdao.close();
			viewDate();

		}

	}

	@Override
	public void onClick(View v) {
		if (button3.getId() == v.getId()) {
			if (type.equals("无")) {
				Toast.makeText(ReportNoRFIDActivity.this, "请选择类型", 1000).show();
				return;
			}
			System.out.println("保存");
			if (imgpath != null && imgpath.size() > 0) {
				showDialog(DIALOG + 1);
			} else {
				Toast.makeText(ReportNoRFIDActivity.this, "这种情况必须拍照", 1000)
						.show();
				return;
			}

		} else if (button4.getId() == v.getId()) {
			if (OrderID < 1) {
				Toast.makeText(this, "还没添加工程单呢", 1000).show();
				return;
			}
			if (isupload) {
				Toast.makeText(this, "已经上传的工程单不能修改", 1000).show();
				return;
			}
			boolean b = modify();
			if (b) {
				Toast.makeText(this, "修改成功", 1000).show();
			} else {
				Toast.makeText(this, "修改失败", 1000).show();
			}
		} else if (button5.getId() == v.getId()) {
			if (OrderID < 1) {
				Toast.makeText(this, "还没添加工程单呢", 1000).show();
				return;
			}
			pd = new ProgressDialog(this);
			pd.setMessage("上传中.....");
			pd.show();
			new Thread() {

				@Override
				public void run() {
					ReportDao dao = new ReportDao(ReportNoRFIDActivity.this);
					List<EngineeringOrderPoVo> lists = dao.queryUpload(OrderID
							+ "");
					if (lists == null || lists.size() < 0) {
						Toast.makeText(ReportNoRFIDActivity.this, "没有数据！", 1000)
								.show();
						return;
					}
					EngineeringOrderPoVo e = dao.queryUpload(OrderID + "").get(
							0);
					dao.close();
					Map<String, String> map1 = new HashMap<String, String>();
					Map<String, String> map3 = new HashMap<String, String>();
					map3.put("desc", e.getDesc());
					map3.put("typeid", e.getTypenumber());
					map3.put("waternumber", e.getWaternumber());
					map3.put("name", e.getName());
					map3.put("latitude", e.getLatitude() + "");
					map3.put("longitude", e.getLongitude() + "");
					Map<File, String> map2 = new HashMap<File, String>();
					SharedPreferenceUtil sh = new SharedPreferenceUtil(
							ReportNoRFIDActivity.this);
					map3.put("imsi", sh.getValue(XmlNameHelper.IMSI));
					List<String> img = e.getImagepath();
					for (int i = 0; i < img.size(); i++) {
						if (img.get(i) != null) {
							File file = new File(img.get(i));
							if (file.exists()) {
								map1.put(file.getName(), "imagename");
								map2.put(file, "imagepath");
							}
						}
					}
					if (e.getSoundpath() != null) {
						File file = new File(e.getSoundpath());
						if (file.exists()) {
							map1.put(file.getName(), "soundname");
							map2.put(file, "soundpath");
						}
					}
					if (e.getVideopath() != null) {
						File file = new File(e.getVideopath());
						if (file.exists()) {
							map1.put(file.getName(), "videoname");
							map2.put(file, "videopath");
						}
					}
					RequestUrl r = new RequestUrl(ReportNoRFIDActivity.this);
					String url = r.getUrl(RequestUrl.UploadOrder);

					String respon = UploadHttpClient.uploadSubmit(url, map1,
							map2, map3);

					if (respon.equals("error")) {
						Message msg = myHandler.obtainMessage();
						msg.what = 1;
						myHandler.sendMessage(msg);
					} else {
						try {
							JSONObject json = new JSONObject(respon);
							String message = json.getString("message");
							if (message.equals("yes")) {
								Message msg = myHandler.obtainMessage();
								msg.what = 2;
								myHandler.sendMessage(msg);
							} else {
								Message msg = myHandler.obtainMessage();
								msg.what = 3;
								myHandler.sendMessage(msg);
							}
						} catch (JSONException e1) {
							Message msg = myHandler.obtainMessage();
							msg.what = 3;
							myHandler.sendMessage(msg);
						}

					}
				}

			}.start();
		}

	}

	/**
	 * 展现数据
	 */
	public void viewDate() {
		textview1.setText("");
		textview2.setText("");
		if (list == null || list.size() < 1) {
			Toast.makeText(this, "没有查到数据", 1000).show();
			return;
		}
		textview1.setText(list.get(i).getWaternumber());
		latitude = list.get(i).getLatitude();
		longitude = list.get(i).getLongitude();
		textview2.setText(list.get(i).getAdds());

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, ITEM0 + 1, 0, "拍照");
		menu.add(0, ITEM0 + 2, 0, "录视频");
		menu.add(0, ITEM0 + 3, 0, "录音");

		menu.findItem(ITEM0 + 1);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ITEM0 + 1:
			if (TextUtils.isEmpty(textview1.getText())) {
				Toast.makeText(ReportNoRFIDActivity.this, "没有找到水表不能操作", 1000)
						.show();
				return false;
			}
			Intent intent = new Intent(ReportNoRFIDActivity.this,
					OrderImageActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("otherid", OrderID + "");
			bundle.putString("status", "1");
			bundle.putString("classname", "ReportNoRFIDActivity");
			intent.putExtras(bundle);
			startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);

			break;
		case ITEM0 + 2:
			if (TextUtils.isEmpty(textview1.getText())) {
				Toast.makeText(ReportNoRFIDActivity.this, "没有找到水表不能操作", 1000)
						.show();
				return false;
			}
			videoMethod();
			break;
		case ITEM0 + 3:
			if (TextUtils.isEmpty(textview1.getText())) {
				Toast.makeText(ReportNoRFIDActivity.this, "没有找到水表不能操作", 1000)
						.show();
				return false;
			}
			System.out.println("录音");
			soundRecorderMethod();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	// 拍摄视频
	private void videoMethod() {
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		FileNameUtil f = new FileNameUtil(this);
		videopath = f.videopath();
		String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date()) + ".avi";
		File out = new File(videopath);
		out = new File(videopath, fileName);
		Uri uri = Uri.fromFile(out);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO);
	}

	/**
	 * 发送短息
	 */
	public void sendMSM(String number, String name) {
		Uri smsToUri = Uri.parse("smsto:" + number);
		Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);

		sendIntent.putExtra("sms_body", "尊敬的" + name + "用户:你的水表已绑定RFID卡");

		startActivity(sendIntent);
		System.out.println("发短息");
	}

	// 录音功能
	private void soundRecorderMethod() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("audio/*");

		startActivityForResult(intent, REQUEST_CODE_TAKE_SOUND);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_TAKE_VIDEO) {
			System.out.println("返回视频");
			if (resultCode == RESULT_OK) {
				videopath = data.getData().toString().substring(7);
				System.out.println(videopath);
			}
		} else if (requestCode == REQUEST_CODE_TAKE_IMAGE) {
			if (resultCode == RESULT_OK) {
				imgpath = data.getStringArrayListExtra("imgpath");
			}
		} else if (requestCode == REQUEST_CODE_TAKE_SOUND) {
			if (resultCode == RESULT_OK) {
				Uri uriVideo = data.getData();
				Cursor cursor = this.getContentResolver().query(uriVideo, null,
						null, null, null);
				if (cursor.moveToNext()) {
					String strVideoPath = cursor.getString(cursor
							.getColumnIndex("_data"));
					FileInputStream fin = null;
					FileOutputStream fout = null;

					File file = new File(strVideoPath);

					try {
						fin = new FileInputStream(file);
						System.out.println(file.isFile());
						FileNameUtil f = new FileNameUtil(this);
						soundpath = f.soundpath();
						if (soundpath == null) {
							Toast.makeText(ReportNoRFIDActivity.this, "SD卡不可用",
									Toast.LENGTH_LONG).show();
							return;
						}
						String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
								.format(new Date()) + ".amr";
						soundpath = soundpath + "/" + fileName;
						System.out.println(soundpath);
						fout = new FileOutputStream(soundpath);

						byte[] buffer = new byte[1024];
						int bytesRead;
						while ((bytesRead = fin.read(buffer)) > 0) {
							System.out.println("---");

							fout.write(buffer, 0, bytesRead);
						}
						fin.close();
						fout.close();
					} catch (FileNotFoundException e) {

						e.printStackTrace();
					} catch (IOException e) {

						e.printStackTrace();
					} finally {
						file.delete();
					}

				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 保存
	 * 
	 * @return
	 */
	public boolean save() {
		boolean b = false;
		ReportDao dao = new ReportDao(this);
		ContentValues values = new ContentValues();
		values.put("ordername", edit2.getEditableText().toString());
		values.put("desc", edit3.getEditableText().toString());
		values.put("waternumber", textview1.getText().toString());
		values.put("soundpath", soundpath);
		values.put("videopath", videopath);
		values.put("latitude", latitude);
		values.put("longitude", longitude);
		values.put("status", "0");

		OrderID = dao.insertReport(values, type);

		if (OrderID > 0) {
			List<ContentValues> lists = new ArrayList<ContentValues>();
			for (int k = 0; k < imgpath.size(); k++) {
				ContentValues value = new ContentValues();
				value.put("otherid", OrderID);
				value.put("status", "1");
				value.put("type", "1");
				value.put("path", imgpath.get(k));

				lists.add(value);
			}
			b = dao.insertALL(lists, DbTableName.RESOURCES);
			dao.close();
		} else {
			return false;
		}

		return b;

	}

	/**
	 * 修改
	 * 
	 * @return
	 */
	public boolean modify() {
		boolean b = false;
		ReportDao dao = new ReportDao(this);
		ContentValues values = new ContentValues();
		values.put("ordername", edit2.getEditableText().toString());
		values.put("desc", edit3.getEditableText().toString());
		values.put("waternumber", textview1.getText().toString());
		values.put("soundpath", soundpath);
		values.put("videopath", videopath);
		values.put("latitude", latitude);
		values.put("longitude", longitude);
		values.put("status", "0");
		b = dao.modifyOrder(values, OrderID + "", type);
		if (OrderID > 0) {
			List<ContentValues> lists = new ArrayList<ContentValues>();
			for (int k = 0; k < imgpath.size(); k++) {
				ContentValues value = new ContentValues();
				value.put("otherid", OrderID);
				value.put("status", "1");
				value.put("type", "1");
				value.put("path", imgpath.get(k));

				lists.add(value);
			}
			b = dao.insertALL(lists, DbTableName.RESOURCES);
		}
		dao.close();
		return b;
	}

	/**
	 * 上传更新消息
	 */
	Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();

			if (msg.what == 2) {
				isupload = true;
				Toast.makeText(ReportNoRFIDActivity.this, "上传成功",
						Toast.LENGTH_LONG).show();
				ReportDao dao = new ReportDao(ReportNoRFIDActivity.this);
				dao.delectImg(OrderID + "");
				dao.delectOrder(OrderID + "");
				dao.close();

			} else {
				Toast.makeText(ReportNoRFIDActivity.this, "上传失败",
						Toast.LENGTH_LONG).show();
			}
		}

	};

	/**
	 * 翻页
	 */
	public void filp() {
		videopath = "";
		soundpath = "";
		imgpath = null;
		OrderID = 0;
		isupload = false;
		if (i < 0) {
			i = 0;
			Toast.makeText(ReportNoRFIDActivity.this, "没有前面的数据了！",
					Toast.LENGTH_LONG).show();
		} else if (i > (list.size() - 1)) {
			i = list.size() - 1;
			Toast.makeText(ReportNoRFIDActivity.this, "没有后面的数据了！",
					Toast.LENGTH_LONG).show();
		} else {
			viewDate();
		}
	}

	@Override
	public boolean onDown(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {

		if (e1.getX() - e2.getX() > verticalMinDistance
				&& Math.abs(velocityX) > minVelocity) {
			if (list != null) {
				i--;
				filp();
			}

		} else {
			if (list != null) {
				i++;
				filp();
			}

		}
		return false;

	}

	@Override
	public void onLongPress(MotionEvent e) {

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {

		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {

		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {

		return mGestureDetector.onTouchEvent(event);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {

		case DIALOG + 1:
			Builder builder1 = new android.app.AlertDialog.Builder(this);
			// 设置对话框的图标
			builder1.setIcon(R.drawable.buttondraw);
			builder1.setTitle("确定添加新的工程单？");
			builder1.setPositiveButton("确定",
					new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (TextUtils.isEmpty(type)) {
								Toast.makeText(ReportNoRFIDActivity.this,
										"你还没选择类型！", Toast.LENGTH_LONG).show();
								return;
							}
							boolean b = save();
							if (b) {
								Toast.makeText(ReportNoRFIDActivity.this,
										"添加数据成功", Toast.LENGTH_LONG).show();

							}

						}
					});
			builder1.setNeutralButton("取消",
					new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

						}
					});
			// 创建一个单选按钮对话框
			dialog = builder1.create();
			break;
		}
		return dialog;
	}

}
